<?php

function output( $method, $data ) {
	$serverid = (int) $_GET['serverid'];

	if( !isset( $_GET['plain'] )) {
		echo 'update.'.$method.'('.intval( $serverid ).', '.json_encode($data).");\n";
	} else {
		echo json_encode($data);
	}
}

try {
	if( !empty( $_GET['package'] )) {
		$data = db()->update_package->get("id = '%s'", $_GET['package'] )->assoc();
		$pkg = new update_package( $data );
		$current = intval( $_GET['current'] );

		output( 'install', $pkg->deliver( $_SERVER['REMOTE_ADDR'], $current ));

		$col = $current ? 'updates' : 'installations';
		db()->query( "UPDATE update_package SET %s = %s + 1 WHERE id = '%s'", $col, $col, $data['id'] );

		if( strpos( $_SERVER['HTTP_HOST'], 'iv-cms.de' ) !== false ) {
			$username = db()->query("SELECT username
				FROM iv_board.wcf1_session
				WHERE ipAddress = '%s'", $_SERVER['REMOTE_ADDR'] )->value();

			db()->update_log->insert(array(
				'package' => $data['id'],
				'ip' => $_SERVER['REMOTE_ADDR'],
				'user' => $username
			));
		}
	} else {
		output( 'remote', array_values( update_package::liste( $_SERVER['REMOTE_ADDR'] )));
	}
} catch( Exception $e ) {
	output('error', array( 'error' => $e->getMessage()));
}

